#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <cstring>
#include <string>
using namespace std;

int main()
{
    int pipefd[2];
    if (pipe(pipefd) == -1)
    {
        perror("pipe");
        return 1;
    }
    pid_t pid=fork();
    if (pid == -1)
    {
        perror("fork");
        return 2;
    }
    else if (pid == 0)//子进程
    {
        //关闭写端
        close(pipefd[1]);
        //读取数据
        char buffer[128];
        ssize_t s=read(pipefd[0],buffer,sizeof(buffer)-1);
        if (s > 0)
        {
            buffer[s] = '\0';
            cout << "child process read data:" << buffer << endl;
        }
        else{
            perror("read");
        }

        //关闭读端
        close(pipefd[0]);
    }
    else//父进程
    {
        //关闭读端
        close(pipefd[0]);
        //写入数据
        const char* str="i am father";
        write(pipefd[1],str,strlen(str)+1);

        //关闭写端
        close(pipefd[1]);
        wait(nullptr);
    }
    return 0;
}